//
//  XRSegmentControl.m
//  XRLoopSegmentControl
//
//  Created by TQS on 15/4/11.
//  Copyright (c) 2015年 寒竹子. All rights reserved.
//

#define SCREEN_SIZE [UIScreen mainScreen].bounds.size
#import "XRSegmentControl.h"

@interface XRSegmentControl()

@property (nonatomic, strong) UIScrollView * topScrollView;
@property (nonatomic, strong) UISegmentedControl * segment;
@property (nonatomic, strong) UIImageView * lineView;
@property (nonatomic, assign) NSInteger selectedIndex; // 选中的index

@end

@implementation XRSegmentControl

- (instancetype)initWithFrame:(CGRect)frame
                       titles:(NSArray *)titles
                     delegate:(id)delegate
                     textFont:(UIFont *)textFont
              normalTextColor:(UIColor *)normalColor
                selectedColor:(UIColor *)selectedColor
                    barHeight:(CGFloat)barHeight
                        image:(UIImage *)image
              backgroundColor:(UIColor *)backgroundColor
                 defaultIndex:(NSInteger)defaultIndex
{
    if (self = [super initWithFrame:frame]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeSegmentIndex:) name:SelectedIndexChanged_Notification object:nil];
        _textFont = textFont;
        _image = image;
        _backgroundColor = backgroundColor;
        _barHeight = barHeight;
        _normalColor = normalColor;
        _selectedColor = selectedColor;
        self.delegate = delegate;
        _defaultIndex = defaultIndex;
        [self setupUIWtihTitles:titles];
    }
    return self;
}

/**
 * @brief   初始化UI
 *
 * @param
 * @return
 */
- (void)setupUIWtihTitles:(NSArray *)titles
{
    _segment = [[UISegmentedControl alloc] initWithItems:titles];
    
    _segment.backgroundColor = _backgroundColor;
    _segment.tintColor = [UIColor clearColor];
    
    CGFloat barWidth;
    
    if (titles.count <= 3) {
        barWidth = self.bounds.size.width / titles.count;
    }else if (titles.count == 4){
        // 3.5等分
        barWidth = self.bounds.size.width / 3.5;
    }else {
        barWidth = self.bounds.size.width / 4.0f;
    }
    
    for (int i = 0; i < _segment.numberOfSegments; i++) {
        [_segment setWidth:barWidth forSegmentAtIndex:i];
    }
    _segment.frame = CGRectMake(0, 0, _segment.numberOfSegments * barWidth, _barHeight);
    [_segment setTitleTextAttributes:[NSDictionary dictionaryWithObjects:@[self.textFont, self.normalColor] forKeys:@[NSFontAttributeName, NSForegroundColorAttributeName]] forState:UIControlStateNormal];
    [_segment setTitleTextAttributes:[NSDictionary dictionaryWithObjects:@[self.textFont, self.selectedColor] forKeys:@[NSFontAttributeName, NSForegroundColorAttributeName]] forState:UIControlStateSelected];
    
    // default selected
    _segment.selectedSegmentIndex = self.defaultIndex;
    _selectedIndex = self.defaultIndex;
    [_segment addTarget:self action:@selector(segmentValueChaned:) forControlEvents:UIControlEventValueChanged];
    
    // topScrollView
    _topScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, _barHeight)];
    _topScrollView.pagingEnabled = YES;
    _topScrollView.bounces = NO;
    _topScrollView.showsHorizontalScrollIndicator = NO;
    _topScrollView.showsVerticalScrollIndicator = NO;
    _topScrollView.contentSize = CGSizeMake(_segment.numberOfSegments * barWidth, 0);
    
    [_topScrollView addSubview:_segment];
    
    _lineView = [[UIImageView alloc] initWithFrame:CGRectMake([_segment widthForSegmentAtIndex:0] * _segment.selectedSegmentIndex + 20.0f, CGRectGetMaxY(_segment.frame) - 1.0f, barWidth - 40.0f, 1.0f)];
    _lineView.image = self.image;
    [_topScrollView addSubview:_lineView];
    
    [self addSubview:_topScrollView];
}

/**
 * @brief   segment值变化
 *
 * @param   segment
 * @return  none
 */
- (void)segmentValueChaned:(UISegmentedControl *)segment
{
    if (_selectedIndex == segment.selectedSegmentIndex) {
        return;
    }
    _selectedIndex = segment.selectedSegmentIndex;

    if ([self.delegate respondsToSelector:@selector(segmentSelectedIndexChanged:)]) {
        [self.delegate segmentSelectedIndexChanged:segment.selectedSegmentIndex];
    }
    
    [UIView animateWithDuration:0.3 animations:^{
        CGRect frame = _lineView.frame;
        frame.origin.x = [segment widthForSegmentAtIndex:0] * segment.selectedSegmentIndex + 20.0f;
        _lineView.frame = frame;
    } completion:^(BOOL finished) {
        
    }];
    
    //  等分 >= screensize.width / [segment widthForSegmentAtIndex:0] - 1
    if (segment.selectedSegmentIndex >= SCREEN_SIZE.width / [segment widthForSegmentAtIndex:0] - 1) {
        if (segment.selectedSegmentIndex == segment.numberOfSegments - 1) {
            return;
        }
        [_topScrollView setContentOffset:CGPointMake([segment widthForSegmentAtIndex:0] * (segment.selectedSegmentIndex - 2), 0) animated:NO];
    }else {
        [_topScrollView setContentOffset:CGPointMake(0, 0) animated:NO];
    }
}

/**
 * @brief   通知方式改变segment的selectedIndex
 *
 * @param   nf
 * @return  none
 */
- (void)changeSegmentIndex:(NSNotification *)nf
{
    NSInteger selectedIndex = [[nf object] integerValue];
    
    _segment.selectedSegmentIndex = selectedIndex;
    
    [UIView animateWithDuration:0.3 animations:^{
        CGRect frame = _lineView.frame;
        frame.origin.x = [_segment widthForSegmentAtIndex:0] * _segment.selectedSegmentIndex + 10;
        _lineView.frame = frame;
    } completion:^(BOOL finished) {
        
    }];
    
    // 等分 >= screensize.width / [segment widthForSegmentAtIndex:0] - 1
    if (_segment.selectedSegmentIndex >= SCREEN_SIZE.width / [_segment widthForSegmentAtIndex:0] - 1) {
        if (_segment.selectedSegmentIndex == _segment.numberOfSegments - 1) {
            return;
        }
        [_topScrollView setContentOffset:CGPointMake([_segment widthForSegmentAtIndex:0] * (_segment.selectedSegmentIndex - 2), 0) animated:NO];
    }else {
        [_topScrollView setContentOffset:CGPointMake(0, 0) animated:NO];
    }
}

@end
